import re
import json

def fix_time_occurred_in_text(text):
    # 匹配 time_occurred 字段中的时间数组格式 [xx:xx.xx] 或 [xx:xx.xx, xx:xx.xx]
    def replace_match(match):
        time_value = match.group(2).strip()
        return f'{match.group(1)}"{time_value}"{match.group(3)}'

    pattern = r'("time_occurred"\s*:\s*)(\[[^]]*\]|\d+:\d+\.\d+)(\s*[,\}\]])'
    fixed_text = re.sub(pattern, replace_match, text)
    return fixed_text

def normalize_json(json_str):
    try:
        data = json.loads(json_str)

        # 如果是行为列表数组（没有外层 key）
        if isinstance(data, list):
            return json.dumps({"behaviors": data}, ensure_ascii=False, indent=2)

        # 如果 key 是 behavior_analysis 或 behavior，则改为 behaviors
        if "behavior_analysis" in data:
            data["behaviors"] = data.pop("behavior_analysis")
        elif "behavior" in data:
            data["behaviors"] = data.pop("behavior")
        elif "behaviors" not in data:
            return json_str

        return json.dumps(data, ensure_ascii=False, indent=2)

    except json.JSONDecodeError:
        return json_str


# 读取原始文件
input_file = '20250625_102224_retry.txt'
with open(input_file, 'r', encoding='utf-8') as f:
    content = f.read()

# 替换所有 time_occurred 中的时间值为字符串格式
fixed_content = fix_time_occurred_in_text(content)

# 正则匹配 JSON 内容并进行标准化处理
json_block_pattern = r'```json\s*([{\[].*?[\}\]])\s*```'

# 存储替换信息 (start, end, replacement)
replacements = []

# 使用 finditer 遍历所有匹配项
for match in re.finditer(json_block_pattern, fixed_content, flags=re.DOTALL):
    raw_json = match.group(1)  # 提取出 JSON 主体部分
    normalized_json = normalize_json(raw_json)
    new_block = f"```json\n{normalized_json}\n```"
    replacements.append((match.start(), match.end(), new_block))

# 从后往前替换，避免索引错乱
replacements.sort(reverse=True)

# 转成可变结构
content_lines = list(fixed_content)

# 逐个替换
for start, end, new_text in replacements:
    content_lines[start:end] = new_text

# 拼接最终结果
processed_content = ''.join(content_lines)

# 写回文件或写入新文件
output_file = input_file + '_fixed.txt'
with open(output_file, 'w', encoding='utf-8') as f:
    f.write(processed_content)

print("✅ 已修复 time_occurred 时间格式，并标准化 JSON 格式，输出至:", output_file)